package ssm.spring.ioc_03;

import jakarta.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;

/**
 * description: 自动装配注解（DI）
 * TODO: 在ioc容器中查找符合类型的组件对象，设置给当前属性
 *
 * 1. `@Autowired(required = false)`属性表示：能装就装，装不上就不装，不报错。不推荐，会出现空指针
 * 2. @Resource(name = "userServiceImpl") = @Autowired + @Qualifier(value = "userServiceImpl")
 */
@Controller
public class UserController {

    @Autowired
//    @Qualifier("newUserServiceImpl")
    private UserService newUserServiceImpl;

    // 如果直接使用@Resource，成员变量名必须是userServiceImpl
    @Resource(name = "userServiceImpl")
    private UserService userServiceImpl;

    public void show(){
        //调用业务层的show
        String show = newUserServiceImpl.show();
        System.out.println("show = " + show);
    }

    public void show2(){
        //调用业务层的show
        String show = userServiceImpl.show();
        System.out.println("show2 = " + show);
    }


    // TODO: Bean组件在IOC容器中只有一个实例对象

    @Autowired
    private CartService cartService;

    @Autowired
    private CartService cartServiceImpl;

    public void testAutowired() {
        cartService.show();
        System.out.println("*****");
        cartServiceImpl.show();
    }

    @Resource
    private CartService cartServiceR;

    @Resource
    private CartService cartServiceImplR;

    public void testResource() {
        cartServiceR.show();
        System.out.println("-----");
        cartServiceImplR.show();
    }
}
